/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.listener;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.request.SimpleRequestMessage;
import cn.easyplatform.messages.vos.EnvVo;
import cn.easyplatform.spi.service.IdentityService;
import cn.easyplatform.type.Constants;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.web.Lifecycle;
import cn.easyplatform.web.contexts.Contexts;
import cn.easyplatform.web.log.LogManager;
import cn.easyplatform.web.service.ServiceLocator;
import org.zkoss.web.servlet.http.Encodes;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.util.Clients;

import java.io.UnsupportedEncodingException;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class LogoutListener implements EventListener<Event> {

    private EnvVo env;

    public LogoutListener(EnvVo env) {
        this.env = env;
    }

    @Override
    public void onEvent(Event event) throws Exception {
        logout(env);
    }

    public final static void logout(EnvVo env) {
        Clients.confirmClose("");
        IdentityService uc = ServiceLocator
                .lookup(IdentityService.class);
        IResponseMessage<?> resp = uc.logout(new SimpleRequestMessage());
        if (resp.isSuccess()) {
            LogManager.stop();
            if (env.getLogoutUrl() != null) {
                Executions.sendRedirect(env.getLogoutUrl());
            } else {
                StringBuilder sb = new StringBuilder();
                sb.append("/login.go");
                if (!Strings.isBlank(env.getAppContext())) {
                    sb.append("?app=").append(env.getAppContext());
                    if (!Strings.isBlank(env.getPortlet()))
                        sb.append("&portlet=").append(env.getPortlet());
                    if (env.getVariables() != null && !env.getVariables().isEmpty()) {
                        try {
                            String query = sb.toString();
                            sb.setLength(0);
                            sb.append(Encodes.setToQueryString(query,
                                    env.getVariables()));
                        } catch (UnsupportedEncodingException e) {
                        }
                    }
                } else {
                    if (!Strings.isBlank(env.getPortlet()))
                        sb.append("?portlet=").append(env.getPortlet());
                    if (env.getVariables() != null && !env.getVariables().isEmpty()) {
                        if (Strings.isBlank(env.getPortlet()))
                            sb.append("?");
                        try {
                            String query = sb.toString();
                            sb.setLength(0);
                            sb.append(Encodes.setToQueryString(query,
                                    env.getVariables()));
                        } catch (UnsupportedEncodingException e) {
                        }
                    }
                }
                Executions.sendRedirect(sb.toString());
                sb = null;
            }
            Session session = Sessions.getCurrent();
            Lifecycle.endSession(session);
            session.removeAttribute(Constants.SESSION_ID);
            session.removeAttribute(Contexts.PLATFORM_APP_ENV);
            session.removeAttribute(Contexts.PLATFORM_USER);
            session.removeAttribute(Contexts.PLATFORM_USER_ORGS);
            session.invalidate();
        }
    }
}
